
import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ExternalLink, Github, Star, Calendar, ChevronDown, ChevronUp, FileText, Code2, Users, Zap } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { format } from 'date-fns';
import ReactMarkdown from 'react-markdown';

// 项目类型图标映射
const projectTypeIcons = {
  'task': Code2,
  'ecommerce': Users,
  'blog': FileText,
  'weather': Zap,
  'default': Code2
};

// 项目类型颜色
const projectTypeColors = {
  'task': 'bg-blue-600 text-blue-600',
  'ecommerce': 'bg-green-600 text-green-600',
  'blog': 'bg-purple-600 text-purple-600',
  'weather': 'bg-orange-600 text-orange-600',
  'default': 'bg-gray-600 text-gray-600'
};

// 获取项目类型
const getProjectType = (projectName) => {
  const name = projectName.toLowerCase();
  if (name.includes('任务') || name.includes('task') || name.includes('管理')) return 'task';
  if (name.includes('电商') || name.includes('ecommerce') || name.includes('商城')) return 'ecommerce';
  if (name.includes('博客') || name.includes('blog') || name.includes('文档')) return 'blog';
  if (name.includes('天气') || name.includes('weather')) return 'weather';
  return 'default';
};

// 项目卡片组件
const ProjectCard = ({ project, index, isFeatured = false }) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const projectType = getProjectType(project.name);
  const TypeIcon = projectTypeIcons[projectType];
  const colorClass = projectTypeColors[projectType];

  const formatDate = (dateString) => {
    if (!dateString) return '';
    return format(new Date(dateString), 'yyyy年MM月');
  };

  const descriptionContent = project.description || '';

  return (
    <motion.div
      initial={{ opacity: 0, y: 30 }}
      whileInView={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.6, delay: index * 0.1 }}
      viewport={{ once: true }}
      className="print:break-inside-avoid"
    >
      <Card className={`transition-all duration-300 hover:shadow-lg print:shadow-none ${
        isFeatured ? 'border-blue-200 bg-blue-50/30' : 'bg-white'
      }`}>
        <CardHeader className="pb-4">
          <div className="flex items-start justify-between">
            <div className="flex items-center gap-3">
              <div className={`w-10 h-10 ${colorClass.split(' ')[0]} rounded-lg flex items-center justify-center flex-shrink-0`}>
                <TypeIcon className="w-5 h-5 text-white" />
              </div>
              <div>
                <h3 className="text-xl font-semibold text-gray-900 leading-tight print:text-lg">
                  {project.name}
                </h3>
                <div className="flex items-center gap-2 mt-1">
                  {isFeatured && (
                    <Badge className="bg-blue-600 text-white text-xs">
                      <Star className="w-3 h-3 mr-1" />
                      特色项目
                    </Badge>
                  )}
                  {(project.start_date || project.end_date) && (
                    <Badge variant="outline" className="text-xs text-gray-600">
                      <Calendar className="w-3 h-3 mr-1" />
                      {formatDate(project.start_date)} - {
                        project.end_date ? formatDate(project.end_date) : '进行中'
                      }
                    </Badge>
                  )}
                </div>
              </div>
            </div>
            
            <div className="flex items-center gap-2 print:hidden">
              {project.link && (
                <Button variant="ghost" size="sm" asChild>
                  <a href={project.link} target="_blank" rel="noopener noreferrer">
                    <ExternalLink className="w-4 h-4" />
                  </a>
                </Button>
              )}
              {project.github && (
                <Button variant="ghost" size="sm" asChild>
                  <a href={project.github} target="_blank" rel="noopener noreferrer">
                    <Github className="w-4 h-4" />
                  </a>
                </Button>
              )}
            </div>
          </div>
        </CardHeader>

        <CardContent className="pt-0">
          {/* 技术栈 */}
          <div className="flex flex-wrap gap-2 mb-4">
            {project.technologies?.map((tech, techIndex) => (
              <Badge 
                key={techIndex} 
                variant="secondary" 
                className="text-xs bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors print:bg-gray-100"
              >
                {tech}
              </Badge>
            ))}
          </div>

          {/* 项目描述 */}
          <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
            <div className={`prose prose-sm max-w-none text-gray-700 leading-relaxed print:text-sm ${
              !isExpanded ? 'line-clamp-3' : ''
            }`}>
              <ReactMarkdown
                components={{
                  h1: ({ children }) => <h1 className="text-lg font-semibold mb-2 print:text-base">{children}</h1>,
                  h2: ({ children }) => <h2 className="text-base font-semibold mb-2 print:text-sm">{children}</h2>,
                  h3: ({ children }) => <h3 className="text-sm font-semibold mb-1 print:text-xs">{children}</h3>,
                  p: ({ children }) => <p className="mb-2 print:mb-1">{children}</p>,
                  ul: ({ children }) => <ul className="list-disc list-inside mb-2 print:mb-1">{children}</ul>,
                  ol: ({ children }) => <ol className="list-decimal list-inside mb-2 print:mb-1">{children}</ol>,
                  li: ({ children }) => <li className="mb-1 print:mb-0">{children}</li>,
                  strong: ({ children }) => <strong className="font-semibold text-gray-900">{children}</strong>,
                  em: ({ children }) => <em className="italic">{children}</em>,
                  code: ({ children }) => <code className="bg-gray-100 px-1 py-0.5 rounded text-sm font-mono">{children}</code>,
                  blockquote: ({ children }) => <blockquote className="border-l-4 border-gray-300 pl-4 italic">{children}</blockquote>,
                }}
              >
                {descriptionContent}
              </ReactMarkdown>
            </div>
            
            {/* 展开/收起按钮 */}
            {descriptionContent && descriptionContent.length > 200 && (
              <CollapsibleTrigger asChild>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  className="mt-2 p-0 h-auto text-blue-600 hover:text-blue-800 print:hidden"
                >
                  {isExpanded ? (
                    <>
                      <ChevronUp className="w-4 h-4 mr-1" />
                      收起
                    </>
                  ) : (
                    <>
                      <ChevronDown className="w-4 h-4 mr-1" />
                      展开详情
                    </>
                  )}
                </Button>
              </CollapsibleTrigger>
            )}
          </Collapsible>

          {/* 项目链接 - 打印时显示 */}
          {(project.link || project.github) && (
            <div className="hidden print:block mt-4 pt-3 border-t border-gray-200">
              <div className="space-y-1 text-sm text-gray-600">
                {project.link && (
                  <div>
                    <span className="font-medium">项目链接:</span> {project.link}
                  </div>
                )}
                {project.github && (
                  <div>
                    <span className="font-medium">源码地址:</span> {project.github}
                  </div>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </motion.div>
  );
};

export default function Projects({ projects }) {
  if (!projects || projects.length === 0) return null;

  const featuredProjects = projects.filter(p => p.featured);
  const otherProjects = projects.filter(p => !p.featured);

  return (
    <section className="py-16 bg-gray-50 print:bg-white print:py-8">
      <div className="max-w-4xl mx-auto px-6 print:px-0">
        {/* 标题 */}
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          viewport={{ once: true }}
          className="text-center mb-12 print:mb-6"
        >
          <h2 className="text-3xl font-light text-gray-900 mb-4 print:text-2xl print:mb-2">
            项目作品
          </h2>
          <div className="h-1 w-16 bg-blue-600 mx-auto mb-4 print:h-0.5 print:w-12 print:mb-2"></div>
          <p className="text-gray-600 max-w-2xl mx-auto print:text-sm">
            以下是我参与开发的主要项目，展示了在不同技术栈和业务场景下的实践经验
          </p>
        </motion.div>

        {/* 特色项目 */}
        {featuredProjects.length > 0 && (
          <div className="mb-12 print:mb-6">
            <div className="flex items-center gap-2 mb-6 print:mb-4">
              <Star className="w-5 h-5 text-yellow-500" />
              <h3 className="text-xl font-semibold text-gray-900 print:text-lg">
                特色项目
              </h3>
            </div>
            <div className="space-y-6 print:space-y-4">
              {featuredProjects.map((project, index) => (
                <ProjectCard
                  key={index}
                  project={project}
                  index={index}
                  isFeatured={true}
                />
              ))}
            </div>
          </div>
        )}

        {/* 其他项目 */}
        {otherProjects.length > 0 && (
          <div>
            <h3 className="text-xl font-semibold text-gray-900 mb-6 print:text-lg print:mb-4">
              其他项目
            </h3>
            <div className="space-y-6 print:space-y-4">
              {otherProjects.map((project, index) => (
                <ProjectCard
                  key={index}
                  project={project}
                  index={index}
                  isFeatured={false}
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
